package com.clouddisk.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.clouddisk.common.exception.BusinessException;

import java.util.Date;

public class JwtUtil {
    // 秘钥
    private static final String SECRET = "cloud-disk-secret";
    // token过期时间：24小时
    private static final long EXPIRATION = 24 * 60 * 60 * 1000L;

    /**
     * 生成token
     */
    public static String createToken(Long userId) {
        Date now = new Date();
        Date expiration = new Date(now.getTime() + EXPIRATION);
        return JWT.create()
                .withClaim("userId", userId)
                .withIssuedAt(now)
                .withExpiresAt(expiration)
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 解析token
     */
    public static Long getUserId(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaim("userId").asLong();
        } catch (JWTVerificationException e) {
            throw new BusinessException(401, "token无效");
        }
    }
} 